package com.bys.admin.ai.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bys.admin.ai.controller.vo.ChatMessagePageReqVO;
import com.bys.admin.ai.controller.vo.ChatMessageSaveReqVO;
import com.bys.admin.ai.controller.vo.ChatMessageSendVO;
import com.bys.admin.ai.entity.Chat;
import com.bys.admin.ai.entity.ChatMessage;
import com.bys.admin.ai.mapper.ChatMessageMapper;
import com.bys.admin.ai.service.ChatMessageService;
import com.bys.admin.ai.service.ChatService;
import com.github.yulichang.base.MPJBaseServiceImpl;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import com.bys.exception.ServiceException;
import static com.bys.constant.ErrorCodeConstant.CHAT_MESSAGE_NOT_EXISTS;
import static com.bys.constant.ErrorCodeConstant.CHAT_NOT_EXISTS;

import java.util.*;
import com.bys.vo.PageVo;
import com.bys.util.BeanUtils;
import reactor.core.publisher.Flux;


/**
 * AI Chat 消息 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class ChatMessageServiceImpl  extends MPJBaseServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService {

    @Resource
    private ChatMessageMapper chatMessageMapper;
    @Resource
    private ChatService chatService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createChatMessage(ChatMessageSaveReqVO createReqVO) {
        // 插入
        ChatMessage chatMessage = BeanUtils.toBean(createReqVO, ChatMessage.class);
        chatMessageMapper.insert(chatMessage);
        // 返回
        return chatMessage.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateChatMessage(ChatMessageSaveReqVO updateReqVO) {
        // 校验存在
        validateChatMessageExists(updateReqVO.getId());
        // 更新
        ChatMessage updateObj = BeanUtils.toBean(updateReqVO, ChatMessage.class);
        chatMessageMapper.updateById(updateObj);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteChatMessage(Long id) {
        // 校验存在
        validateChatMessageExists(id);
        // 删除
        chatMessageMapper.deleteById(id);
    }

    private void validateChatMessageExists(Long id) {
        if (chatMessageMapper.selectById(id) == null) {
            throw new ServiceException(CHAT_MESSAGE_NOT_EXISTS);
        }
    }
    @Override
    public ChatMessage getChatMessage(Long id) {
        return chatMessageMapper.selectById(id);
    }
    @Override
    public Page<ChatMessage> getChatMessagePage(ChatMessagePageReqVO pageReqVO) {
    return chatMessageMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ChatMessage> listByChatId(Long chatId) {
        return list(new LambdaQueryWrapper<ChatMessage>()
                .eq(ChatMessage::getChatId, chatId)
                .orderByAsc(ChatMessage::getId));
    }

    @Override
    public Flux<Boolean> sendChatMessageStream(ChatMessageSendVO chatMessageSendVO, Long userId) {
        Chat chat = chatService.getById(chatMessageSendVO.getChatId());
        if (Objects.isNull(chat) ||   ObjUtil.notEqual(chat.getUserId(), userId)) {
            throw new ServiceException(CHAT_NOT_EXISTS);
        }
        // 2. 插入 user 发送消息
        ChatMessage userMessage = createChatStreamMessage(chat.getId(), null, chat.getModel(),chat.getModelId(),
                userId, chat.getRoleId(), MessageType.USER, chatMessageSendVO.getContent(), chatMessageSendVO.getUseContext());
        return null;
    }

    private ChatMessage createChatStreamMessage(Long id, Long replyId, String model, Long modelId, Long userId, Long roleId, MessageType messageType, String content, Boolean useContext) {
        return null;
    }
}